import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;


public class Utils {

	
	public static ArrayList<Utterance> processMessagesList(Elements messages, String topicId){
		ArrayList<Utterance> result = new ArrayList<Utterance>();
		int i=0;
		for (Iterator<Element> it = messages.iterator(); it.hasNext();) {
			i++;
			Element el = (Element) it.next();
			Utterance u = new Utterance(i, topicId);
			processMessage(el,u);
			result.add(u);
		}
		
		return result;
	}
	
	
//	for (ListIterator iterator = list.listIterator(list.size()); iterator.hasPrevious();) {
// 	  final Object listElement = iterator.previous();
//  }
//" &quot; ' &apos; < &lt; > &gt; & &amp;
	public static String escapeText(String s){
		
		s = s.replaceAll("&", "&amp;");
		s = s.replaceAll("\"", "&quot;");
		s = s.replaceAll("'", "&apos;");
		s = s.replaceAll("<", "&lt;");
		s = s.replaceAll(">", "&gt;");
		return s;
	}
	
	
	public static void processMessage(Element m, Utterance u){
		String id = m.attr("id");
		String subject = m.getElementById(id+"-subject").text();
		String author = m.getElementById(id+"-postedBy").text();
		String time = m.getElementById(id+"-postedAt").text();
		String content = m.getElementById(id+"-detail").text();
		
		int level = 0;
		Element tbody = m.getElementsByTag("tbody").get(0);
		Element tr = tbody.getElementsByTag("tr").get(0);
		Element td = tr.getElementsByTag("td").get(0);
		String style = td.attr("style").trim();
		level = Integer.parseInt(style.substring(style.lastIndexOf(':')+1,style.lastIndexOf("px;")))/25;
		
		u.setMsgId(id);
		u.setSubject(subject);
		u.setUserId(author);
		u.setUtteranceTime(time);
		u.setText(content);
		u.setLevel(level);
		System.out.println(td.attr("style").trim()+"#"+level+"#");
	//	System.out.println(m);
		
	}
	
	
	public static List<String> getTopicFiles() {
		return getFiles(".html", "in/");
	}
	
	public static List<String> getCSVFiles() {
		return getFiles(".csv", "in-csv/");
	}
	
	public static List<String> getFiles(String sufix, String dir) {
		List<String> retList	= new ArrayList<String>();
		File f 					= new File (dir + ".");
		String [] list			= f.list();
		
		if ( list != null && list.length > 0) {
			for (int i = 0; i < list.length; i++) {
				String filename = list[i];
				if ( filename.endsWith(sufix) ) {
					retList.add(filename);
				}
				
			}
		}
		
		return retList;
	}
	
	
}